package com.sheng.config;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ClassPathXmlApplicationContext implements ApplicationContext {
    private Map<String ,Object> map=new HashMap<>();
    public ClassPathXmlApplicationContext(String xmlPath) {
        try {
            InputStream in = ClassPathXmlApplicationContext.class.getClassLoader().getResourceAsStream(xmlPath);;
            SAXReader saxReader = new SAXReader();
            Document document = saxReader.read(in);
            Element rootElement = document.getRootElement();
            System.out.println(rootElement);
            List<Element> list = rootElement.selectNodes("//bean");
            for (Element element : list) {
                String clazz = element.attributeValue("class");

                String id = element.attributeValue("id");
                Class cls = Class.forName(clazz);
                Object obj = cls.newInstance();
                map.put(id,obj);
                //依赖注入
                List<Element> propertys = element.elements("propertys");
                for (Element property : propertys) {

                    String name = element.attributeValue("name");
                    String ref = element.attributeValue("ref");
                    Object o = map.get(ref);
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, cls);
                    Method method = propertyDescriptor.getWriteMethod();
                    //反射执行set方法
                    method.invoke(obj,o);
                }


            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object getBean(String id) {
        return map.get(id);
    }
}
